package it.uniroma2.exp;

import it.uniroma2.util.math.MatrixUtils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * @author lorenzo
 * 
 * This class gets as inputs a CDS matrix and some vectors to be processed,
 * then applies the matrix to the vectors and extracts a snapshot of the "activated" matrix,
 * printing it as a byte array.
 *
 */
public class CDSActivationMatrixExtractor {

	double[][] drpMatrix;
	double[][] inputs;
	File[] outputFiles;
	
	/**
	 * @param args:
	 * 1 - file containing cds matrix
	 * 2 - file containing the input vectors as a matrix
	 * 3 - base output file name (several copies will be created, one for each input vector)
	 */
	public static void main(String[] args) {
		if (args.length < 3) {
			System.out.println("Missing parameters (matrix file, input vectors file, base output file name)");
			return;
		}
		CDSActivationMatrixExtractor extractor;
		try {
			extractor = new CDSActivationMatrixExtractor(args[0], args[1], args[2]);
			extractor.activateAndExtract();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public CDSActivationMatrixExtractor(String drpMatrixFile, String inputFile, String outputFile) throws Exception {
		drpMatrix = MatrixUtils.loadDenseMatrix(new File(drpMatrixFile), 0);
		inputs = MatrixUtils.loadDenseMatrix(new File(inputFile), 0);
		outputFiles = new File[inputs.length];
		for (int i=0; i<inputs.length; i++)
			outputFiles[i] = new File(outputFile+"_"+i);
	}
	
	public void activateAndExtract() throws Exception {
		for (int i=0; i<inputs.length; i++) {
			if (i>0 && i%100==0)
				System.out.println(i);
			System.out.print(".");
			DataOutputStream output = new DataOutputStream(new FileOutputStream(outputFiles[i]));
			for (int k=0; k<drpMatrix[0].length; k++) {
				for (int j=0; j<inputs[i].length; j++) {
					output.writeDouble(drpMatrix[j][k]*inputs[i][j]);
				}
				int filling = (3 - ((inputs[i].length * (Double.SIZE/8)) % 3)) % 3;
				for (int f=0; f<filling; f++)
					output.write(0);
			}
		}
	}

}
